<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket Demo</title>
</head>
<body>
    <input id="text" type="text" />
    <button onclick="send()">发送消息</button>
    <button onclick="startWebSocket()">开始连接</button>
    <button onclick="closeWebSocket()">关闭连接</button>
    <div id="message" />
</body>
<script type="text/javascript">
    let websocket = null;
    let clientId = Math.random().toString(36).substr(2);

    //开始连接WebSocket
    function startWebSocket(){
        if(websocket === null || websocket.readyState === WebSocket.CLOSED){
            //仅当没有已存在的WebSocket连接或已关闭时创建新的WebSocket连接
            websocket = new WebSocket("ws://localhost:8080/ws/"+clientId);
            
            //设置连接成功回调
            websocket.onopen = function(){
                setMessageInnerHTML("连接成功");
            };
            
            //设置错误处理回调
            websocket.onerror = function(){
                setMessageInnerHTML("连接失败");
            };
            
            //设置接收消息回调
            websocket.onmessage = function(event){
                setMessageInnerHTML(event.data);
            };
            
            //设置连接关闭回调
            websocket.onclose = function(){
                setMessageInnerHTML("连接已关闭");
            };
        } else {
            setMessageInnerHTML("已经连接，请勿重复连接！");
        }
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接
    window.onbeforeunload = function(){
        if (websocket && websocket.readyState !== WebSocket.CLOSED) {
            websocket.close();
        }
    };

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //发送消息
    function send(){
        var message = document.getElementById('text').value;
        if (websocket && websocket.readyState === WebSocket.OPEN) {
            websocket.send(message);
            setMessageInnerHTML("客户端发送的消息: "+message);
        } else {
            setMessageInnerHTML("请先建立连接再发送消息！");
        }
    }

    //关闭连接
    function closeWebSocket() {
        if (websocket && websocket.readyState !== WebSocket.CLOSED) {
            websocket.close();
            websocket = null;  //重置websocket变量
        }
    }
</script>
</html>
